package gorseclient

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

func (c *DefaultGorse) CreateItem(fullUrl string, itemId, comment, isHidden string, labels, category []string) error {
	// 创建一个包含所有参数的map
	data := url.Values{}
	data.Set("itemId", itemId) // 使用Set简化单个值的添加
	data.Set("comment", comment)
	data.Set("isHidden", isHidden)
	if len(labels) > 0 {
		for _, v := range labels {
			data.Add("labels", v)
		}
	}
	if len(category) > 0 {
		for _, v := range category {
			data.Add("category", v)
		}
	}

	resp, err := http.Post(fullUrl+"/api/forum/recommended/createItem", "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("data", data.Encode()))
		return err
	}
	defer resp.Body.Close() // 确保响应体被关闭

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		// 可以根据需要处理不同的状态码
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return err
	}

	return nil
}

func (c *DefaultGorse) DeleteItem(fullUrl string, ids string) error {
	// 创建一个包含所有参数的map
	data := url.Values{}
	data.Set("ids", ids)

	resp, err := http.Post(fullUrl+"/api/forum/recommended/createItem", "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("data", data.Encode()))
		return err
	}
	defer resp.Body.Close() // 确保响应体被关闭

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		// 可以根据需要处理不同的状态码
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return err
	}

	return nil
}

func (c *DefaultGorse) UpdateItem(fullUrl string, itemId, comment, isHidden string, labels, category []string) error {
	// 创建一个包含所有参数的map
	data := url.Values{}
	data.Set("itemId", itemId) // 使用Set简化单个值的添加
	data.Set("comment", comment)
	data.Set("isHidden", isHidden)
	if len(labels) > 0 {
		for _, v := range labels {
			data.Add("labels", v)
		}
	}
	if len(category) > 0 {
		for _, v := range category {
			data.Add("category", v)
		}
	}

	resp, err := http.Post(fullUrl+"/api/forum/recommended/updateItem", "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("data", data.Encode()))
		return err
	}
	defer resp.Body.Close() // 确保响应体被关闭

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		// 可以根据需要处理不同的状态码
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return err
	}

	return nil
}

func (c *DefaultGorse) GetItemNeighbors(fullUrl, tid, uid, offset, pageSize string) (map[string]any, error) {
	// Create a new request
	req, err := http.NewRequest("GET", fullUrl+"/api/forum/recommended/itemNeighborList", nil)
	if err != nil {
		logx.Errorw("[GORSE] Error creating request:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// Add query parameters
	q := req.URL.Query()
	q.Add("uid", uid)
	q.Add("tid", tid)
	q.Add("offset", offset)
	q.Add("pageSize", pageSize)
	req.URL.RawQuery = q.Encode()

	// Send the request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("query", q.Encode()))
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(resp.Body) // Ensure the response body is closed

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		// 可以根据需要处理不同的状态码
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return nil, err
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorw("[GORSE] Error reading response body:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// 解析JSON响应
	result := make(map[string]any)
	if err := json.Unmarshal(body, &result); err != nil {
		logx.Errorw("[GORSE] Error parsing JSON response:", logx.Field("detail", err.Error()), logx.Field("response_body", string(body)))
		return nil, err
	}

	return result, nil
}

func (c *DefaultGorse) GetItemPopular(fullUrl, uid, offset, pageSize string) (map[string]any, error) {
	// Create a new request
	req, err := http.NewRequest("GET", fullUrl+"/api/forum/recommended/itemPopularList", nil)
	if err != nil {
		logx.Errorw("[GORSE] Error creating request:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// Add query parameters
	q := req.URL.Query()
	q.Add("uid", uid)
	q.Add("offset", offset)
	q.Add("pageSize", pageSize)
	req.URL.RawQuery = q.Encode()

	// Send the request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("query", q.Encode()))
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(resp.Body) // Ensure the response body is closed

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		// 可以根据需要处理不同的状态码
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return nil, err
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorw("[GORSE] Error reading response body:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// 解析JSON响应
	result := make(map[string]any)
	if err := json.Unmarshal(body, &result); err != nil {
		logx.Errorw("[GORSE] Error parsing JSON response:", logx.Field("detail", err.Error()), logx.Field("response_body", string(body)))
		return nil, err
	}

	return result, nil
}

func (c *DefaultGorse) GetItemLatest(fullUrl, uid, offset, pageSize string) (map[string]any, error) {
	// Create a new request
	req, err := http.NewRequest("GET", fullUrl+"/api/forum/recommended/itemLatestList", nil)
	if err != nil {
		logx.Errorw("[GORSE] Error creating request:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// Add query parameters
	q := req.URL.Query()
	q.Add("uid", uid)
	q.Add("offset", offset)
	q.Add("pageSize", pageSize)
	req.URL.RawQuery = q.Encode()

	// Send the request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("query", q.Encode()))
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(resp.Body) // Ensure the response body is closed

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		// 可以根据需要处理不同的状态码
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return nil, err
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorw("[GORSE] Error reading response body:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// 解析JSON响应
	result := make(map[string]any)
	if err := json.Unmarshal(body, &result); err != nil {
		logx.Errorw("[GORSE] Error parsing JSON response:", logx.Field("detail", err.Error()), logx.Field("response_body", string(body)))
		return nil, err
	}

	return result, nil
}

func (c *DefaultGorse) GetRecommendItemByCategory(fullUrl, uid, offset, pageSize, category string) (map[string]any, error) {
	// Create a new request
	req, err := http.NewRequest("GET", fullUrl+"/api/forum/recommended/itemByCategory", nil)
	if err != nil {
		logx.Errorw("[GORSE] Error creating request:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// Add query parameters
	q := req.URL.Query()
	q.Add("uid", uid)
	q.Add("offset", offset)
	q.Add("pageSize", pageSize)
	q.Add("category", category)
	req.URL.RawQuery = q.Encode()

	// Send the request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logx.Errorw("[GORSE] Error calling the API:", logx.Field("detail", err.Error()), logx.Field("url", fullUrl), logx.Field("query", q.Encode()))
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(resp.Body) // Ensure the response body is closed

	// Check HTTP response status code
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("received non-200 response code: %d", resp.StatusCode)
		logx.Errorw("[GORSE] Non-success HTTP response:", logx.Field("detail", err.Error()), logx.Field("status_code", resp.StatusCode))
		return nil, err
	}

	// Read response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorw("[GORSE] Error reading response body:", logx.Field("detail", err.Error()))
		return nil, err
	}

	// Parse JSON response
	result := make(map[string]any)
	if err := json.Unmarshal(body, &result); err != nil {
		logx.Errorw("[GORSE] Error parsing JSON response:", logx.Field("detail", err.Error()), logx.Field("response_body", string(body)))
		return nil, err
	}

	return result, nil
}
